//
//  OtherFileFolderViewController.m
//  MyVocalNovels
//
//  Created by mac on 2019/5/25.
//  Copyright © 2019 YangYang. All rights reserved.
//

#import "OtherFileFolderViewController.h"
#import "AlbumModel.h"
#import "FolderModel.h"

@interface OtherFileFolderViewController ()<UITableViewDelegate, UITableViewDataSource>

@property (nonatomic, strong) UITableView *tableView;
@property (nonatomic, strong) NSArray *dataSource;

@property (nonatomic, strong) NSMutableArray *songListArr;

@end

@implementation OtherFileFolderViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    [self initTableView];
    self.dataSource = [self getAllFolderName:_folderPath];
    
    
    
    
    
    [self.tableView reloadData];
}

-(void)initTableView
{
    _tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, kScreenHeight) style:UITableViewStylePlain];
    [self.view addSubview:_tableView];
    _tableView.dataSource = self;
    _tableView.delegate = self;
    [_tableView registerClass:[UITableViewCell class] forCellReuseIdentifier:@"UITableViewCell"];
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"UITableViewCell"];
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    FolderModel *model = self.dataSource[indexPath.row];
    cell.textLabel.text = model.folderName;
    return cell;
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.dataSource.count;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    //    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    FolderModel *model = self.dataSource[indexPath.row];
    NSLog(@"model = %@",model);
    __weak typeof(self) weakSelf = self;
    NSString *path = model.folderPath;
    NSString *extensionString = [[path pathExtension] lowercaseString];
    if ([extensionString isEqualToString:@"text"]) {
        
    }
    else if ([extensionString isEqualToString:@"mp3"] || [extensionString isEqualToString:@"m4a"])
    {
        dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
        dispatch_async(queue, ^{
            NSLog(@"[NSThread currentThread] = %@",[NSThread currentThread]);
            [weakSelf createOtherFolderFile];
        });
        
        
        
        AlbumModel *model = self.songListArr[indexPath.row];
        MusicPlayingViewController *musicPlayingVC = [MusicPlayingViewController sharedInstance];
        musicPlayingVC.navigationItem.title = model.songName;
        musicPlayingVC.playListModels = self.songListArr;
        musicPlayingVC.currentPlayIndex = indexPath.row;
        [musicPlayingVC play:model];
        BackItemView
        [self.navigationController pushViewController:musicPlayingVC animated:YES];
        
        
    }
    else
    {
        OtherFileFolderViewController *otherFileFolderVC = [[OtherFileFolderViewController alloc] init];
        otherFileFolderVC.navigationItem.title = model.folderName;
        otherFileFolderVC.folderPath = model.folderPath;
        otherFileFolderVC.folderName = model.folderName;
        BackItemView
        [self.navigationController pushViewController:otherFileFolderVC animated:YES];
    }
}

-(NSMutableArray *)songListArr
{
    if (!_songListArr) {
        _songListArr = [NSMutableArray new];
        NSInteger i = 0;
        for (FolderModel *folderModel in self.dataSource) {
            
//            NSString *songFullName = [musicPath lastPathComponent];
            AlbumModel *model = [[AlbumModel alloc] init];
            NSString *songName = [folderModel.folderName stringByDeletingPathExtension];
            NSString *songExtensionName = [folderModel.folderName pathExtension];
            model.songName = songName;
            model.songExtensionName = songExtensionName;
            model.songPath = [LibraryFolder stringByAppendingPathComponent:folderModel.folderPath];
            model.type = WorksSourceTypeLocal;
            model.downloadFolderName = songName;
            
//            musicDic[@"albumImage"] = [NSString stringWithFormat:@"album_%ld.jpg",(i % 4)];
//            musicDic[@"singerImage"] = [NSString stringWithFormat:@"%ld.jpg",(i % 4)];
//            NSInteger currentImage = i % _images.count;
//            NSDictionary *albumDic = _images[currentImage];
            model.albumImage = [NSString stringWithFormat:@"album_%ld.jpg",(i % 4)];
            model.singerImage = [NSString stringWithFormat:@"%ld.jpg",(i % 4)];
            i++;
            
            [self.songListArr addObject:model];
        }
    }
    return _songListArr;
}

-(void)createOtherFolderFile
{
    
    NSLog(@"[NSThread currentThread] = %@",[NSThread currentThread]);
    
    NSMutableArray *folderArr = [NSMutableArray new];
    NSFileManager *fileManager = [NSFileManager defaultManager];
    if ([fileManager fileExistsAtPath:OtherOpenFilePath]) {
        NSLog(@"文件已存在");
        
        
        NSArray *otherFolderArr = [NSArray arrayWithContentsOfFile:OtherOpenFilePath];
        [folderArr addObjectsFromArray:otherFolderArr];
        
        for (NSDictionary *dic in otherFolderArr) {
            NSString *folderName = dic[@"folderName"];
            if ([_folderName isEqualToString:folderName]) {
                NSLog(@"该文件已经保存过了，无需再次保存");
                return;
            }
            
        }
        
        
    }
    else
    {
        NSLog(@"文件不存在");
    }
    NSInteger i = 0;
    NSMutableArray *fileArr = [NSMutableArray new];
    for (FolderModel *folderModel in self.dataSource) {
//        NSLog(@"[folderModel.folderName pathExtension] = %@",[folderModel.folderName pathExtension]);
        if ([folderModel.folderName isEqualToString:@".DS_Store"]) {
            continue;
        }
        
        NSMutableDictionary *musicDic = [[NSMutableDictionary alloc] init];
        
        musicDic[@"musicName"] = [folderModel.folderName stringByDeletingPathExtension];
        musicDic[@"extensionName"] = [folderModel.folderName pathExtension];
        musicDic[@"musicFullName"] = folderModel.folderName;
        musicDic[@"songPath"] = folderModel.folderPath;
        musicDic[@"albumName"] = folderModel.folderName;
        musicDic[@"singerName"] = folderModel.folderName;
        musicDic[@"writer"] = folderModel.folderName;
        musicDic[@"videoURL"] = @"";
        
        musicDic[@"albumImage"] = [NSString stringWithFormat:@"album_%ld.jpg",(i % 4)];
        musicDic[@"singerImage"] = [NSString stringWithFormat:@"%ld.jpg",(i % 4)];
        [fileArr addObject:musicDic];
        i++;
    }
    NSMutableDictionary *otherFileDic = [NSMutableDictionary new];
    otherFileDic[@"folderName"] = _folderName;
    otherFileDic[@"folders"] = fileArr;
    
    
    
    [folderArr addObject:otherFileDic];
//    __weak typeof(self) weakSelf = self;
//    NSString *otherFolerPath = OtherOpenFilePath;
    if ([folderArr writeToFile:OtherOpenFilePath atomically:YES]) {
        
        dispatch_queue_t queue = dispatch_get_main_queue();
        dispatch_async(queue, ^{
            NSLog(@"[NSThread currentThread] = %@",[NSThread currentThread]);
            [[NSNotificationCenter defaultCenter] postNotificationName:ChangeMusicListNotification object:nil];
//            [[NSNotificationCenter defaultCenter] postNotificationName:@"addSongList" object:nil userInfo:@{@"folderName":weakSelf.folderName,@"folders":fileArr,@"downloadSongFileFolderPath":weakSelf.folderPath}];
        });
        
        
        
        
        
        
        NSLog(@"OtherOpenFilePath = %@",OtherOpenFilePath);
        NSLog(@"文件写入成功");
    }
    else
    {
        NSLog(@"文件写入失败");
    }
    
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 40;
}

-(NSArray *)getAllFolderName:(NSString *)folderPath
{
    NSFileManager *fileManager = [NSFileManager defaultManager];
    
    NSString *currentFolder = [LibraryFolder stringByAppendingPathComponent:folderPath];
    NSArray * dirArray = [fileManager contentsOfDirectoryAtPath:currentFolder error:nil];
    
    NSMutableArray *folderSortArr = [NSMutableArray new];
    for (NSString *fileName in dirArray) {
        if ([fileName isEqualToString:@".DS_Store"]) {
            continue;
        }
        NSString *currentFileName = (NSString *)fileName;
        NSString *currentFilePath = [_folderPath stringByAppendingPathComponent:fileName];
        NSMutableDictionary *folderDic = [[NSMutableDictionary alloc] init];
        folderDic[@"folderName"] = currentFileName;
        folderDic[@"folderPath"] = currentFilePath;
        [folderSortArr addObject:folderDic];
    }
    
    NSArray *sortArr = [NSArray arrayWithObject:[NSSortDescriptor sortDescriptorWithKey:@"folderName" ascending:YES]];
    [folderSortArr sortUsingDescriptors:sortArr];
    
    
    NSMutableArray *folderArr = [NSMutableArray new];
    for (NSDictionary *fileDic in folderSortArr) {
        
        NSString *currentFileName = fileDic[@"folderName"];
        NSString *currentFilePath = fileDic[@"folderPath"];
        FolderModel *model = [[FolderModel alloc] init];
        model.folderName = currentFileName;
        model.folderPath = currentFilePath;
        [folderArr addObject:model];
    }
    
    return [NSArray arrayWithArray:folderArr];
}

//-(NSArray *)dataSource
//{
//    if (_dataSource) {
//        _dataSource = [NSArray new];
//    }
//    return _dataSource;
//}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
